<?php
namespace App;

use Model\Model;
use Model\Red;

class ArticleController extends BaseController
{
    function get($request){
        $model = new Model();
        //做保护
        $st = $model->prepare("select `article` from `tbArticles`");
        $st->execute();
        $articles = $st->fetchAll();
        $article = '<div>';
        foreach ($articles as $k=>$v){
            $article .= '<p>'.$v['article'].'</p>';
        }
        $article .= '</div>';
        $this->assign('articles',$article);
        $html = $this->display('articleList.html');
        $this->response($html);
    }

    function post($request){
        $uid = $request['uid'];
        if(!$uid){
            $this->response('先登录再发文章');
        }
        $article = $this->valid('article',$request);
        $model = new Model();
        $st = $model->prepare("insert into `tbArticles` (`article`,`uid`) values (?,?)");
        $st->bindParam(1, $article);
        $st->bindParam(2, $uid);
        $res = $st->execute();
        if($res){
            $redis = new \Redis();
            $redis->connect('127.0.0.1', 6379);
            //发奖逻辑
            //看数量
            $num = $redis->get('cdkeynum');
            if($num <= 2000) {
                //加锁
                $lock = $redis->setnx("userlock:{$uid}", 1);
                if ($lock) {
                    $key = $redis->rPop('cdkey');
                    $st = $model->prepare("insert into `tbCdKey` (`no`,`uid`) values (?,?)");
                    $st->bindParam(1, $key);
                    $st->bindParam(2, $uid);
                    $res = $st->execute();
                    if (!$res) {
                        $redis->lPush('cdkey', $key);
                    }else{
                        $redis->incr('cdkeynum');
                    }
                }
                $redis->del("userlock:{$uid}");
            }
            $this->response('发表成功');
        }else{
            $this->response('发表失败');
        }

    }

}